package com.trust.pams.util;

import com.chasonx.common.config.JWTConst;
import com.chasonx.common.config.RedisTemplateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @Project : tscp-platform
 * @Author : Chasonx<zc.x>
 * @CreateTime : 2019/12/6 16:03
 * @Desc :
 * @Version : 1.0
 */
@Component
public class CacheUtil {

    private static final String[] strArr = {"1","2","3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"};

    private static RedisTemplateUtils redisTemplateUtils;

    @Autowired
    public void setRedisTemplateUtils(RedisTemplateUtils redisTemplateUtils) {
        CacheUtil.redisTemplateUtils = redisTemplateUtils;
    }

    public static void setUserTokenAndExpire(String id , String value){
        setUserTokenAndExpire(id , value , JWTConst.JWT_EXPIRATION_HALF_HOUR);
    }

    public static void setUserTokenAndExpire(String id,String value,long expire){
        redisTemplateUtils.set(id , value);
        refreshUserToken( id , expire );
    }

    public static void refreshUserToken(String id ) {
        refreshUserToken(id , JWTConst.JWT_EXPIRATION_HALF_HOUR);
    }

    public static void refreshUserToken(String id , long expire){
        redisTemplateUtils.expire( id , expire);
    }

    public static void deleteUserToken(String id){
        redisTemplateUtils.del( id );
    }

    public static void setCaptchaCache(String id,String value){
        redisTemplateUtils.set( id , value);
        redisTemplateUtils.expire( id , 60 * 5);
    }

    public static boolean isCaptchaExpire(String id){
        return redisTemplateUtils.get( id ) == null;
    }

    public static boolean validateCaptcha(String id,String captchaStr){
        Object value = redisTemplateUtils.get(id);
        if(value == null || !value.toString().toLowerCase().equals( captchaStr.toLowerCase() )){
            return false;
        }
        return true;
    }

    public static String getCaptchaCode(){
        Random random = new Random();
        String code = "";
        for(int i = 0;i < 6;i++){
            code += strArr[random.nextInt(strArr.length)].toUpperCase();
        }
        return code;
    }

    public static void removeCaptchaCode(String key){
        redisTemplateUtils.del(key);
    }

    public static void main(String[] args) {
        for (int i = 0;i < 10;i++)
            System.out.println(CacheUtil.getCaptchaCode());
    }
}
